package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.common.util.RequestUtils;
import com.mars.common.util.TokenUtils;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.module.admin.entity.*;
import com.mars.module.admin.mapper.SysProductMapper;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysShopCarRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.mars.module.admin.mapper.SysShopCarMapper;
import org.springframework.beans.BeanUtils;
import com.mars.module.admin.entity.SysShopCar;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysShopCarService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 购物车业务层处理
 *
 * @author mars
 * @date 2024-01-30
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysShopCarServiceImpl implements ISysShopCarService {

    private final SysShopCarMapper baseMapper;
    private final SysUserMapper userMapper;
    private final SysProductMapper productMapper;
    private final TokenUtils tokenUtils;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysShopCar add(SysShopCarRequest request) {
        SysShopCar entity = SysShopCar.builder().build();
        BeanUtils.copyProperties(request, entity);
        Long id = ContextUserInfoThreadHolder.get().getId();
        entity.setUserId(id);
        List<SysShopCar> shopCarList = baseMapper.selectList(new QueryWrapper<SysShopCar>().eq("user_id", id).eq("product_id", request.getProductId()));
        if (!shopCarList.isEmpty()) {
            SysShopCar sysShopCar = shopCarList.stream().findFirst().orElse(null);
            if (sysShopCar != null) {
                entity.setTotal(entity.getTotal() + 1);
                baseMapper.updateById(entity);
            }
        } else {
            entity.setTotal(1);
            baseMapper.insert(entity);
        }
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysShopCarRequest request) {
        SysShopCar entity = SysShopCar.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysShopCar getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<SysShopCar> pageList(SysShopCarRequest request) {
        HttpServletRequest servletRequest = RequestUtils.getRequest();
        Long userId = tokenUtils.getUserId(servletRequest);
        request.setUserId(userId);
        Page<SysShopCar> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysShopCar> query = this.buildWrapper(request);
        IPage<SysShopCar> pageRecord = baseMapper.selectPage(page, query);
        List<SysShopCar> records = pageRecord.getRecords();
        List<SysShopCar> recordsNew = new ArrayList<>();
        for (SysShopCar shopCar : records) {
            SysUser user = userMapper.selectById(shopCar.getUserId());
            SysProduct product = productMapper.selectById(shopCar.getProductId());
            shopCar.setUserName(user == null ? "" : user.getUserName());
            shopCar.setProductName(product == null ? "" : product.getName());
            shopCar.setPicture(product == null ? "" : product.getPicture());
            shopCar.setPrice(product == null ? new BigDecimal(0) : product.getPrice());
            recordsNew.add(shopCar);
        }
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<SysShopCar> list(SysShopCarRequest request) {
        LambdaQueryWrapper<SysShopCar> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<SysShopCar> buildWrapper(SysShopCarRequest param) {
        LambdaQueryWrapper<SysShopCar> query = new LambdaQueryWrapper<>();
        if (param.getProductName() != null) {
            List<SysProduct> product = productMapper.selectList(new QueryWrapper<SysProduct>().like("name", param.getProductName()));
            //获取商品ID
            List<Long> collect = product.stream().map(p -> p.getId()).collect(Collectors.toList());
            if (!collect.isEmpty()) {
                query.in(SysShopCar::getProductId, collect);
            } else {
                query.eq(SysShopCar::getProductId, 0);
            }
        }
        if (param.getUserId() != null) {
            query.eq(SysShopCar::getUserId, param.getUserId());
        }
        return query;
    }

}
